import { Component, HostListener, OnDestroy, OnInit } from "@angular/core";
import { sjgzxinModuledatas } from "../pubcomponent/pageTitle.datas";
import { CommService } from "../comm-service";
import { MyhttpService } from "../myhttp.service";
import { LocalStorageService } from "../local-storage-service";

declare var $: any;
declare var AMap: any;

@Component({
  template: `
  <div class="all_bg paddingTop">
    <div class="">
        <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
        </div>
      <div class="portlet-body">
        <div class="row">
          <form class="form-horizontal" role="form">
            <div class="col-lg-4 col-lg-offset-7">
              <div class="form-group">
                <label class="control-label col-lg-3" for="cxtj">查询条件：</label>
                <div class="col-lg-8">
                  <input type="text" id="cxtj" placeholder="保密室名称/考点名称/试卷包名称" class="form-control" name="cxtj"
                         [(ngModel)]="s_obj.cxtj"/>
                </div>
              </div>
            </div>

            <div class="col-lg-1">
              <button type="button" class="btn blue" (click)="inittable_sjbcrk()">
                <i class="fa fa-search"></i> 搜索
              </button>
            </div>
          </form>
        </div>
        <div class="row">
          <div class="col-lg-12">
            <my-table [o]="table_sjbcrk"></my-table>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="addressModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog bigmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">地址</h4>
          </div>
          <div class="modal-body">
            <div id="mapdiv" class="mapdiv"></div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="xq_Modal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">出入库试卷信息</h4>
          </div>
          <div class="modal-body">
            <div class="sjbssqkRoom iecrollkf chromescrollkf">
              <ul class="list-group" *ngIf="tlineDatas.length">
                <li class="list-group-item tlineitem" *ngFor="let item of tlineDatas;index as index">
                  <div class="pull-left circleroom">
                 <span [ngClass]="{'endcircle':item.status<0,'ingcircle':item.status==0,'circle':item.status>0}">
                   <i class="fa fa-circle"></i>
                 </span>
                    <div class="vertical_line"
                         [ngClass]="{'endvline':item.status<0,'ingvline':item.status==0,'vline':item.status>0}"></div>
                  </div>
                  <div class="pull-left tsitem">
                  <span *ngIf="item.zt==0"
                        style="display: inline-block;width: 100%;height: 100%;line-height: 30px; text-align: center; background-color: #2094F2;color: #ffffff">运送开始</span>
                    <span *ngIf="item.zt==-1"
                          style="display: inline-block;width: 100%;height: 100%;line-height: 30px; text-align:center; background-color: #FD5354;color: #ffffff">运送结束</span>
                  </div>
                  <div class="pull-left xxitem">
                    <span class="time">{{item.tline}}</span>
                    <span class="marker" *ngIf="item.marker_e">{{item.marker_b}}<span
                      style="color: #FE8564">出库</span>{{item.marker_e}}</span>
                    <span class="marker" *ngIf="!item.marker_e">{{item.marker_b}}<span
                      style="color: #6CBB70">入库</span></span>
                  </div>
                  <div class="clearfix"></div>
                </li>
              </ul>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>
  <div>
  `,
  styles: [
    ".mapdiv{width: 100%;height:600px;}",
    ".sjbssqkRoom{width: calc(100% - 17px);margin-top: 10px;height:300px;overflow-y: auto}",
    ".tlineitem{border: none;padding: 0px;margin: 0px}",
    ".tlineitem>.circleroom{width:40px; height: 30px;text-align: center;position: relative;padding-top: 5.5px}",
    ".circleroom>.vertical_line{position: absolute;left: 19.5px;top: 0px;width: 1px;height: 30px;}",
    ".tlineitem>.tsitem{width: 80px;height: 30px;}",
    ".tlineitem>.xxitem{width: calc(100% - 120px);height: 30px;line-height: 30px}",
    ".xxitem>.time{display: inline-block;width: 150px;text-align: center}",
    ".xxitem>.marker{display: inline-block;width: auto;padding-left: 10px}",
    ".endcircle{color: #ADDFE6}",
    ".ingcircle{color:#F9332A }",
    ".circle{color: #39A1F4;}",
    ".endvline{background-color: #ADDFE6}",
    ".ingvline{background-color: #F9332A}",
    ".vline{background-color: #39A1F4}",
  ]
})
export class TjbbSjbcktjComponent implements OnInit, OnDestroy {
  userinfo: any;
  sysBase: string = '2';
  btns: any[] = ["sjcrk_dc"];
  c_btns: any[] = ["xq_sjcrk"];
  hascbtns: any[] = [];
  actionobj1: any[] = [];

  s_obj: any = {
    ksjhbh: "",
    ksgljgid: "",
    cxtj: ""  // 查询条件：保密室名称/考点名称/试卷包名称
  };
  table_sjbcrk: any;
  sjbztKeyValue: any = {
    ycwck: "印厂未出库",
    ycck: "印厂出库",
    bmsrk: "保密室入库",
    bmsck: "保密室出库",
    kdrk: "考点入库",
    kdck: "考点出库",
    pjdrk: "评卷点入库"
  };


  nowaddressMarker: any;
  map: any;
  geocoder: any;

  caozuo_sjbbh: string = "";
  getdatalockid: any;
  getdataIntervalnum: number = 30000;

  tlineDatas: any[] = [];

  /**
   * 初始化按钮
   */
  initactions(): void {
    // this.commservice.getroleBtns(this.btns, this.c_btns, this.userinfo.nowroleid, "table_sjbcrk", (hasportbtns, hastablebtns) => {
    //   this.actionobj1 = hasportbtns;
    //   this.hascbtns = hastablebtns;
    // });
    this.commservice.getroleBtns_not_permissions(this.btns, this.c_btns, "table_sjbcrk", (hasportbtns, hastablebtns) => {
      this.actionobj1 = hasportbtns;
      this.hascbtns = hastablebtns;
    })
  }

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;

    const actiontype = e.type;
    if (fromv === "table_sjbcrk") {
      if (actiontype === "dc") {
        // 导出

      }
    }
  }

  /**
   * 出入库的表格
   */
  inittable_sjbcrk(): void {
    const that = this;
    this.table_sjbcrk = {
      tableid: "table_sjbcrk",
      url: "sjgz/zsymtjbb/sjbcrktj",
      reqobj: this.s_obj,
      sidePagination: "server",
      pageSize: 10,
      pageList: [10, 20, 30],
      total: "totalRows",
      rows: "sjbcrktjList",
      columns: [{
        title: '序号',
        field: "ordernum"
      }, {
        title: "保密室名称",
        field: "bmsmc",
      }, {
        title: "考点名称",
        field: "mdkdmc",
      }, {
        title: "试卷包名称",
        field: "sjbmc",
      }, {
        title: "试卷包状态",
        field: "sjbzt",
        formatter: function (v) {
          return that.sjbztKeyValue[v ? v : ""] ? that.sjbztKeyValue[v ? v : ""] : "";
        }
      }, {
        title: "出/入库地址",
        field: "sjbbh",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.glcsjd;
          const wdv = row.glcswd;
          let str: string = "";
          if (jdv && wdv) {
            if (v.indexOf("|") == -1) {
              str += "<span class='getAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>查看地址</span>";
            } else {
              str += v.substring(1);
            }
          }
          return str;
        }
      }, {
        title: "经纬度",
        field: "showdz",
        events: this.myevents,
        formatter: function (v, row) {
          const jdv = row.glcsjd;
          const wdv = row.glcswd;
          let str: string = "";
          if (jdv && wdv) {
            const position = [jdv, wdv];
            str += "<span class='showAddress' style='cursor: pointer;text-decoration-line: underline;color: blue'>" + position.join("/") + "</span>";
          }
          return str;
        }
      }, {
        title: "详情",
        field: "caozuo",
        events: this.myevents,
        formatter: function (v) {
          let str: string = "";
          if (that.hascbtns.indexOf("xq_sjcrk") != -1) {
            str += "<button type='button' class='btn btn-xs btn-info xq_yjjy'><i class='fa fa-search'></i> 详情</button>";
          }
          return str;
        }
      }]
    };
    if (this.sysBase == "61") {
      this.table_sjbcrk.pageSize = 50;
      this.table_sjbcrk.pageList = [50];
      this.table_sjbcrk.hiddenPageinfoLink = true;
      this.table_sjbcrk.paginationLoop = true;
      this.table_sjbcrk.paginationPreText = "<i class='fa fa-arrow-left'></i>上一页";
      this.table_sjbcrk.paginationNextText = "下一页<i class='fa fa-arrow-right'></i>";
      this.table_sjbcrk.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
    } else {
      this.table_sjbcrk.height = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 240 - 50;
    }
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .getAddress": function (e, value, row, index) {
      const glcsjdv = row.glcsjd;
      const glcswdv = row.glcswd;
      if (glcsjdv && glcswdv) {
        this.getAddresss([glcsjdv, glcswdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          const Flagbit = "|";
          $("#table_sjbcrk").bootstrapTable("updateCell", { index: index, field: "sjbbh", value: Flagbit + dzmc });
        });
      }
    }.bind(this),
    "click .showAddress": function (e, value, row, index) {
      const glcsjdv = row.glcsjd;
      const glcswdv = row.glcswd;
      if (glcsjdv && glcswdv) {
        this.nowaddressMarker.setPosition([glcsjdv, glcswdv]);
        this.getAddresss([glcsjdv, glcswdv], (resp) => {
          const dzmc = resp.regeocode.formattedAddress;
          this.nowaddressMarker.setLabel({
            offset: new AMap.Pixel(10, 0),  //设置文本标注偏移量
            content: dzmc,
            direction: 'bottom' //设置文本标注方位
          })
        });
        this.map.setZoomAndCenter(10, [glcsjdv, glcswdv]);
        $("#addressModal").modal({
          keyboard: true,
          backdrop: "static"
        });
      }
    }.bind(this),
    "click .xq_yjjy": function (e, value, row, index) {
      //实时 出入库试卷信息
      this.caozuo_sjbbh = row.sjbbh;
      if (this.getdatalockid) {
        clearInterval(this.getdatalockid);
      }
      this.getData();
      this.getdatalockid = setInterval(() => {
        this.getData();
      }, this.getdataIntervalnum)
      $("#xq_Modal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this)
  }


  getData(): void {
    if (!this.caozuo_sjbbh) {
      this.tlineDatas.length = 0;
      return
    }
    const url = "sjgz/zsymbmsjkd/sjblzrz";
    this.itservice.kwPtPost(url, {
      sjbbh: this.caozuo_sjbbh
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const sjblzrzListv = resp.sjblzrzList ? resp.sjblzrzList : [];
            if (!sjblzrzListv.length) {
              this.tlineDatas.length = 0;
              return
            }
            this.tlineDatas = sjblzrzListv.map((item) => {
              const jlsjv = item.jlsj; // 记录时间
              const crklxv = item.crklx; // 出入库类型：1 出库；2入库
              const cfdlxv = item.cfdlx; // 发地类型：ysc/bms/bzhkd
              const cfdmcv = item.cfdmc; // 出发地名称
              const mddlxv = item.mddlx; // 目的地类型：bms/bzhkd/smd
              const mddmcv = item.mddmc;  // 目的地名称
              const newobj = {
                tline: jlsjv,
                marker_b: "",
                marker_e: "",
                status: 1, // 初始化都是将来时 , 圈的颜色
                zt: 1  //1  不显示   0 --开始  -1 结束
              };
              if (crklxv == "1") {
                //出库
                newobj.marker_b = `试卷包从【${cfdmcv}】`;
                newobj.marker_e = `，送往【${mddmcv}】`;
                if (cfdlxv == "ysc") {
                  newobj.zt = 0;
                }


              } else {
                // 入库
                newobj.marker_b = `试卷包在【${mddmcv}】`;
                if (mddlxv == "smd") {
                  newobj.zt = -1;
                }
              }
              return newobj;
            });
            this.tlineDatas = this.tlineDatas;
            this.handerLine();
          }
        }
      });
    });
  }

  /**
   * status
   * -1  ---过去时 --灰
   * 0  --进行时 ---红
   * 1----将来时 ---蓝
   */
  handerLine(): void {
    if (!this.tlineDatas.length) {
      return
    }
    const nowms = Date.now(); //ms
    const data_mintime = this.tlineDatas[this.tlineDatas.length - 1]["tline"]; // 倒序
    const data_maxtime = this.tlineDatas[0]["tline"];
    const data_minms = this.commservice.convertTimeToInt(data_mintime);  // ms
    const data_maxms = this.commservice.convertTimeToInt(data_maxtime); // ms
    if (nowms < data_minms) {
      // -无穷  data_minms）
      this.tlineDatas.forEach((item) => {
        item.status = 1; // 都在将来时
      });
      this.tlineDatas[this.tlineDatas.length - 1]["status"] = 0;
    } else if (nowms < data_maxms) {
      // 【data_minms  data_maxms)
      let nowindex: number;
      this.tlineDatas.forEach((item, index) => {
        const ittlinev = item.tline;
        const itlinems = this.commservice.convertTimeToInt(ittlinev); // ms
        const itprelienms = this.tlineDatas[index - 1] ? this.commservice.convertTimeToInt(this.tlineDatas[index - 1]["tline"]) : 0;
        if (nowms == itlinems) {
          nowindex = index;
          item["tline"] = 0;
          for (let i = 0; i < nowindex; i++) {
            this.tlineDatas[i]["tline"] = 1;
          }
          for (let j = (nowindex + 1); j < this.tlineDatas.length; j++) {
            this.tlineDatas[j]["tline"] = -1;
          }
        }
        if (nowms > itlinems && nowms < itprelienms) {
          for (let i = 0; i < nowindex; i++) {
            this.tlineDatas[i]["tline"] = 1;
          }
          for (let j = nowindex; j < this.tlineDatas.length; j++) {
            this.tlineDatas[j]["tline"] = -1;
          }
        }
      });
    } else {
      //【data_maxms +无穷
      this.tlineDatas.forEach((item) => {
        item.status = -1;
      });
      this.tlineDatas[0]["status"] = 0;
    }
  }


  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    });
    this.nowaddressMarker = new AMap.Marker({
      map: that.map,
      //position: markobj.position,
      offset: new AMap.Pixel(-17, -14),
      //angle: Number(markobj.fxj) + 90 + 180,
      zIndex: 100,  //默认值是100
    });

    AMap.plugin(['AMap.Geocoder'],
      function () {
        that.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
      });
  }

  getAddresss(lnglatXY: any, callback: Function): void {
    this.geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        callback(result);
      }
    });
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      this.s_obj.ksgljgid = info.csid;
      this.initactions(); //用户按钮权限
    });
  }

  constructor(private commservice: CommService,
    private itservice: MyhttpService,
    private localStorageService: LocalStorageService) {

  }

  ngOnInit() {
    this.s_obj.ksjhbh = this.localStorageService.get("hksjh");
    this.getuserinfo();
    this.initMap();
    this.commservice.getSysmsg2((resp) => {
      // this.sysBase = resp.sysBase;
      this.inittable_sjbcrk();
    });
  }

  ngOnDestroy() {
    if (this.getdatalockid) {
      clearInterval(this.getdatalockid);
    }
  }

}
